package com.hanock.sm.fork2d;

import java.util.Stack;

import android.util.Log;

public class SceneManager {
	
	
	private static SceneManager instance = null;
	
	public static synchronized SceneManager getInstance(){
		if (instance == null){
			instance = new SceneManager();
		}
		return instance;
	}
	
	
	
	
	// --------------------------------------------------------------------------------------------------------------
	
	private Stack<Scene> sceneStack;
	
	private SceneManager() {
		sceneStack = new Stack<Scene>();
	}
	
	public synchronized void pushScene(Scene scene){
		sceneStack.push(scene);
		scene.setDirty(true);
		
		Log.i("test", "push: " + scene.getClass());
	}
	
	public synchronized void replaceScene(Scene scene){
		if (sceneStack.isEmpty()){
			sceneStack.push(scene);
			Log.i("test", "push: " + scene.getClass());
		}
		else{
			Scene s = sceneStack.pop();
			if (s != null)
				Log.i("test", "pop: " + s.getClass());
			sceneStack.push(scene);
			Log.i("test", "push: " + scene.getClass());
		}
		scene.setDirty(true);
	}
	
	public synchronized void popScene(){
		if (sceneStack.isEmpty())
			return;

		Scene s = sceneStack.pop();
		if (s != null)
			Log.i("test", "pop: " + s.getClass());
		
		Scene scene = getCurrentScene();
		if (scene != null)
			scene.setDirty(true);
	}
	
	public synchronized void backToScene(int tag){
		
		Scene target = null;
		for (Scene sc: sceneStack){
			if (sc.getTag() == tag){
				target = sc;
				break;
			}
		}
		
		if (target == null)
			return;
		
		while (!sceneStack.isEmpty()){
			Scene sc = sceneStack.peek();
			if (sc == target)
				break;
			else{
				sceneStack.pop();
				if (sc != null)
					Log.i("test", "pop: " + sc.getClass());
			}
		}
		
		target.setDirty(true);
	}
	
	public synchronized void backToScene(Class<? extends Scene> clazz){
		
		Scene target = null;
		for (Scene sc: sceneStack){
			if (sc.getClass() == clazz){
				target = sc;
				break;
			}
		}
		
		if (target == null)
			return;
		
		while (!sceneStack.isEmpty()){
			Scene sc = sceneStack.peek();
			if (sc == target)
				break;
			else{
				sceneStack.pop();
				if (sc != null)
					Log.i("test", "pop: " + sc.getClass());
			}
		}
		
		target.setDirty(true);
	}
	
	public synchronized Scene getCurrentScene(){
		
		if (sceneStack.isEmpty())
			return null;
		else
			return sceneStack.peek();
	}
}
